<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar
      title="标题"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.phone"
        name="phoen"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { validator: phoneCheck, message: '手机格式有误请重新填写' }
        ]"
      />
      <van-field
        v-model="form.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^[a-zA-Z0-9]{6,12}$/, message: '请输入正确格式的密码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" :isLoading='isLoading' native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/services/user'
export default {
  name: 'login',
  data () {
    return {
      form: {
        phone: '18201288771',
        password: '111111'
      },
      isLoading: false
    }
  },
  methods: {
    async onSubmit () {
      this.isLoading = true
      const { data } = await login(this.form)
      console.log(data)
      if (data.state === 1) {
        this.$toast.success('登陆成功')
        // 将用户信息存储到state种
        this.$store.commit('setUser', data.content)
        // 跳转 query
        this.$router.push(this.$route.query.redirect || '/')
      } else {
        this.$toast.fail('登陆失败')
      }
      this.isLoading = false
    },
    phoneCheck (value) {
      return /^1\d{10}$/.test(value)
    },
    onClickLeft () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
